package nancal.mp.mvc.dev

import io.swagger.annotations.*
import nancal.mp.db.mongo.*
import nancal.mp.db.mongo.entity.dev.*
import nancal.mp.model.SwaggerModel
import nancal.mp.model.SwaggerRequestDef
import nancal.mp.model.toParameterDefine
import nancal.mp.mvc.dev.ApiDefineAutoController.CnTypeEnum.*
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.*
import nbcp.base.db.CodeName
import nbcp.base.enums.ApiParameterTypeEnum
import nbcp.base.enums.HttpMethod
import nbcp.base.exception.ParameterInvalidException
import nbcp.base.extend.*
import nbcp.base.model.ApiDocDefine
import nbcp.base.model.ApiSimpleParameterDefine
import nbcp.base.model.HttpInvoke
import nbcp.mvc.sys.*
import nbcp.myoql.db.mongo.*
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import javax.servlet.http.*

/**
 * Created by CodeGenerator at 2023-10-16 23:06:13
 */
@Api(description = "Api定义", tags = arrayOf("ApiDefine"))
@RestController
@RequestMapping("/dev/api-define")
class ApiDefineAutoController {

    enum class CnTypeEnum(var remark: String) {
        CnInName("名称含中文"),
        NoCnInName("名称无中文"),
        CnInField("字段含中文"),
        NoCnInField("字段无中文");
    }

    @ApiOperation("列表")
    @PostMapping("/list")
    fun list(
        productLine: String,
        app: String,
        group: String,
        text: String,
        cnType: CnTypeEnum?,
        ids: Array<String>, //当列表列新一条后，刷新时使用
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>
    ): ListResult<ApiDefine> {

        mor.dev.apiDefine.query()
            .apply {
                if (ids.any()) {
                    this.where { it.id mongoIn ids }
                }

                if (productLine.HasValue) {
                    this.linkOr(
                        { it.productLine.code mongoEquals productLine },
                        { it.productLine.name mongoEquals productLine })
                }

                if (app.HasValue) {
                    this.where { it.app mongoLike app }
                }

                if (group.HasValue) {
                    this.where { it.group mongoLike group }
                }

                if (cnType != null) {
                    when (cnType) {
                        CnInName -> this.where { it.name mongoPattern """\W""" }
                        NoCnInName -> this.where { it.name mongoPattern """^\w+$""" }
                        CnInField -> this.linkOr(
                            { it.requestBodyParameters mongoPattern """\W""" },
                            { it.requestHeaderParameters mongoPattern """\W""" },
                            { it.requestUrlPathParameters mongoPattern """\W""" },
                            { it.requestUrlQueryParameters mongoPattern """\W""" }
                        )

                        NoCnInField -> this.where(
                            """function(){
    var allEn = function(ary){  
        for(var i in ary) { 
            var remark = ary[i].remark;
            if( !remark){
                continue;
            }
            
            if( /\W/.test( remark ) ) {  return false   }  
        }  
        return true  
    };
                    
    return  ( this.requestHeaderParameters.length == 0  || allEn( this.requestHeaderParameters ) )
             &&
            (this.requestUrlPathParameters.length == 0 ||  allEn (this.requestUrlPathParameters) )
            &&
            (this.requestUrlQueryParameters.length == 0 ||  allEn (this.requestUrlQueryParameters) )
             &&
            (this.responseHeaderParameters.length == 0 ||  allEn (this.responseHeaderParameters) )
             &&
            (this.requestBodyParameters.items.length == 0 ||  allEn (this.requestBodyParameters.items) )
             &&
            (this.responseBodyParameters.items.length == 0 ||  allEn (this.responseBodyParameters.items) ) 
}
"""
                        )
                    }
                }

                if (text.HasValue) {
                    this.linkOr(
                        { it.productLine.code mongoLike text },
                        { it.productLine.name mongoLike text },
                        { it.app mongoLike text },
                        { it.group mongoLike text },
                        { it.name mongoLike text },
                        { it.url mongoLike text },
                        { it.remark mongoLike text })
                }
            }
            .withPager(query)
            .orderByAsc { it.productLine.name }
            .orderByAsc { it.group }
            .orderByAsc { it.url }
            .toListResult()
            .apply {
                return this;
            }
    }


    @PostMapping("/list-app")
    fun listApp(): List<String> {
        return mor.dev.apiDefine.query()
            .selectDistinct { it.app }
            .toList(String::class.java)
    }

    @GetMapping("/http-client/download")
    fun download(profile: String) {

    }

    data class IdGroup(var id: String = "", var group: String = "");
    @PostMapping("/save-group")
    fun saveGroup(@org.springframework.web.bind.annotation.RequestBody data: Array<IdGroup>): JsonResult {
        data.forEach { setOne ->
            mor.dev.apiDefine.updateById(setOne.id)
                .set { it.group to setOne.group }
                .exec()
        }

        return JsonResult();
    }

    data class IdApp(var id: String = "", var app: String = "");
    @PostMapping("/save-app")
    fun saveApp(@org.springframework.web.bind.annotation.RequestBody data: Array<IdApp>): JsonResult {
        data.forEach { setOne ->
            mor.dev.apiDefine.updateById(setOne.id)
                .set { it.app to setOne.app }
                .exec()
        }

        return JsonResult();
    }

    data class IdProductLine(var id: String = "", var productLine: String);
    @PostMapping("/save-product-line")
    fun saveProductLine(@org.springframework.web.bind.annotation.RequestBody data: Array<IdProductLine>): JsonResult {
        var pls = data.map { it.productLine }.toSet();
        var productLines = mor.dev.productLine.query()
            .linkOr({ it.code mongoIn pls }, { it.name mongoIn pls })
            .toList();

        data.forEach { setOne ->
            var pl = productLines.firstOrNull { it.code == setOne.productLine || it.name == setOne.productLine };
            if (pl == null) {
                return@forEach
            }

            mor.dev.apiDefine.updateById(setOne.id)
                .set { it.productLine to pl }
                .exec()
        }

        return JsonResult();
    }

//    class ImportDataModel {
//        var swaggerUrl = ""
//        var swaggerJson = ""
//        var part = ""
//        var productLineCode = ""
//        var app = ""
//        var excludeModuleStyle = arrayOf<String>()
//        var excludeModuleContent = ""
//        var excludeUrlContent = ""
//        var excludeNameContent = ""
//        var removePrefix = ""
//        var override: Boolean? = null
//    }

    @PostMapping("/import-api")
    fun importApi(
        file: MultipartFile?,
        apiUrl: String,
        productLineCode: String,
        app: String,
        includeModuleStyle: Array<String>,
        excludeModuleStyle: Array<String>,
        includeApiStyle: Array<String>,
        excludeApiStyle: Array<String>,
        excludeModuleContent: String,
        excludeUrlContent: String,
        excludeNameContent: String,
        removePrefix: String,
        override: Boolean?
    ) {
        var jsonText = "";
        if (apiUrl.HasValue) {
            var http = HttpInvoke()
            http.url = (apiUrl);
            http.requestMethod = "GET"
            var res = http.doInvoke()

            jsonText = res.responseText!!
        } else if (file != null) {
            jsonText = file.inputStream.readContentString();
        } else {
            throw ParameterInvalidException("缺少api-doc内容参数")
        }

        if (jsonText.isEmpty()) {
            throw ParameterInvalidException("找不到api-doc内容")
        }


        var productLine = mor.dev.productLine
            .queryByCode(productLineCode)
            .toEntity()
            .must()
            .elseThrow { "找不到产品线" }

        lateinit var list: List<ApiDocDefine>
        if (jsonText.startsWith("[")) {
            list = jsonText.FromListJson(ApiDocDefine::class.java);
        } else if (jsonText.startsWith("{")) {
            list = jsonText.split("\n").filter { it.HasValue }.map { it.FromJson(ApiDocDefine::class.java)!! }
        } else {
            throw ParameterInvalidException("json格式不合法")
        }

        if (list.size == 0) {
            throw ParameterInvalidException("没有接口数据")
        }

        list = list
            .filter { api ->
                if (api.url.isEmpty()) {
                    return@filter false;
                }

                if (excludeUrlContent.HasValue && api.url.contains(excludeUrlContent, true)) {
                    return@filter false;
                }

                if (excludeNameContent.HasValue && api.name.contains(excludeNameContent, true)) {
                    return@filter false;
                }

                var tag = api.group

                if (excludeModuleContent.HasValue && tag.contains(excludeModuleContent, true)) {
                    return@filter false;
                }

                if (excludeModuleStyle.contains("mb") && tag.startsWith("[") && tag.endsWith("]")) {
                    return@filter false;
                }

                if (excludeModuleStyle.contains("sb") && tag.startsWith("(") && tag.endsWith(")")) {
                    return@filter false;
                }

                if (excludeModuleStyle.contains("lb") && tag.startsWith("{") && tag.endsWith("}")) {
                    return@filter false;
                }

                if (excludeApiStyle.contains("mb") && api.name.startsWith("[") && api.name.endsWith("]")) {
                    return@filter false;
                }

                if (excludeApiStyle.contains("sb") && api.name.startsWith("(") && api.name.endsWith(")")) {
                    return@filter false;
                }

                if (excludeApiStyle.contains("lb") && api.name.startsWith("{") && api.name.endsWith("}")) {
                    return@filter false;
                }

                if (includeModuleStyle.size > 0) {
                    var s1 = includeModuleStyle.any {
                        if (it == "mb" && tag.startsWith("[") && tag.endsWith("]")) {
                            return@any true;
                        }
                        if (it == "sb" && tag.startsWith("(") && tag.endsWith(")")) {
                            return@any true;
                        }

                        if (it == "lb" && tag.startsWith("{") && tag.endsWith("}")) {
                            return@any true;
                        }
                        return@any false
                    };
                    if (!s1) {
                        return@filter false;
                    }
                }

                if (includeApiStyle.size > 0) {
                    var s2 = includeApiStyle.any {
                        if (it == "mb" && api.name.startsWith("[") && api.name.endsWith("]")) {
                            return@any true;
                        }
                        if (it == "sb" && api.name.startsWith("(") && api.name.endsWith(")")) {
                            return@any true;
                        }

                        if (it == "lb" && api.name.startsWith("{") && api.name.endsWith("}")) {
                            return@any true;
                        }
                        return@any false
                    };
                    if (!s2) {
                        return@filter false;
                    }
                }


                return@filter true;
            }
            .map {
                var ret = it.ConvertJson(ApiDefine::class.java);

                ret.productLine = CodeName(productLine.code, productLine.name);
                if (app.HasValue) {
                    ret.app = app;
                }

                if (removePrefix.HasValue) {
                    if (it.url.startsWith(removePrefix, true)) {
                        it.url = it.url.Slice(removePrefix.length);
                    }
                }
                return@map ret;
            }


        list.forEach { api ->

            var ent = mor.dev.apiDefine.query()
                .where { it.productLine.code mongoEquals api.productLine.code }
                .where { it.app mongoEquals api.app }
                .where { it.url mongoEquals api.url }
                .toEntity();

            if (ent != null) {
                if (override != null && override) {
                    api.id = ent.id;
                    mor.dev.apiDefine.updateWithEntity(api).execUpdate();
                }
            } else {
                mor.dev.apiDefine.doInsert(api);
            }
        }

    }


    @PostMapping("/import-swagger")
    fun import(
        @RequestParam("file") file: MultipartFile?,
        swaggerUrl: String,
        part: String,
        productLineCode: String,
        app: String,
        includeModuleStyle: Array<String>,
        excludeModuleStyle: Array<String>,
        includeApiStyle: Array<String>,
        excludeApiStyle: Array<String>,
        excludeModuleContent: String,
        excludeUrlContent: String,
        excludeNameContent: String,
        removePrefix: String,
        override: Boolean?
    ) {
        var jsonText = "";
        if (swaggerUrl.HasValue) {
            var http = HttpInvoke();
            http.url = (swaggerUrl)
            http.requestMethod = "GET"
            var res = http.doInvoke()
            jsonText = res.responseText!!
        } else if (file != null) {
            jsonText = file.inputStream.readContentString();
        } else {
            throw ParameterInvalidException("缺少Swagger内容参数")
        }

        if (jsonText.isEmpty()) {
            throw ParameterInvalidException("找不到Swagger内容")
        }


        var productLine = mor.dev.productLine
            .queryByCode(productLineCode)
            .toEntity()
            .must()
            .elseThrow { "找不到产品线" }
        var json = jsonText.FromJson<SwaggerModel>()!!;

        json.paths.keys.toSet().forEach { key ->
            var value = json.paths[key];
            if (value == null) {
                json.paths.remove(key);
                return@forEach
            }


            if (excludeUrlContent.HasValue && key.contains(excludeUrlContent, true)) {
                json.paths.remove(key);
                return@forEach
            }


            var list = listOf(value.get, value.post, value.put, value.delete)
                .filter { it != null }
                .map { it!! }
            if (list.isNullOrEmpty()) {
                json.paths.remove(key);
                return@forEach
            }


            list.forEach for2@{ obj ->
                if (excludeNameContent.HasValue && obj.summary.contains(excludeNameContent, true)) {
                    json.paths.remove(key);
                    return@forEach
                }

                obj.tags.forEach { it ->
                    var tag = it.trim()

                    if (excludeModuleContent.HasValue && tag.contains(excludeModuleContent, true)) {
                        json.paths.remove(key);
                        return@forEach
                    }


                    if (excludeModuleStyle.contains("mb") && tag.startsWith("[") && tag.endsWith("]")) {
                        json.paths.remove(key);
                        return@forEach
                    }

                    if (excludeModuleStyle.contains("sb") && tag.startsWith("(") && tag.endsWith(")")) {
                        json.paths.remove(key);
                        return@forEach
                    }

                    if (excludeModuleStyle.contains("lb") && tag.startsWith("{") && tag.endsWith("}")) {
                        json.paths.remove(key);
                        return@forEach
                    }

                    if (excludeModuleContent.HasValue && tag.contains(excludeModuleContent, true)) {
                        json.paths.remove(key);
                        return@forEach
                    }
                }

                if (excludeApiStyle.contains("mb") && obj.summary.startsWith("[") && obj.summary.endsWith("]")) {
                    json.paths.remove(key);
                    return@forEach
                }

                if (excludeApiStyle.contains("sb") && obj.summary.startsWith("(") && obj.summary.endsWith(")")) {
                    json.paths.remove(key);
                    return@forEach
                }

                if (excludeApiStyle.contains("lb") && obj.summary.startsWith("{") && obj.summary.endsWith("}")) {
                    json.paths.remove(key);
                    return@forEach
                }
            }
        }



        if (includeModuleStyle.size > 0 || includeApiStyle.size > 0) {
            //再处理包含
            var paths = mutableSetOf<String>();

            json.paths.keys.toSet().forEach { key ->
                var value = json.paths[key];
                if (value == null) {
                    json.paths.remove(key);
                    return@forEach
                }

                var list = listOf(value.get, value.post, value.put, value.delete)
                    .filter { it != null }
                    .map { it!! }
                if (list.isNullOrEmpty()) {
                    json.paths.remove(key);
                    return@forEach
                }


                list.forEach for2@{ obj ->
                    if (includeModuleStyle.size > 0) {
                        obj.tags.forEach { it ->
                            var tag = it.trim()

                            if (includeModuleStyle.contains("mb") && tag.startsWith("[") && tag.endsWith("]")) {
                                paths.add(key);
                                return@forEach
                            }

                            if (includeModuleStyle.contains("sb") && tag.startsWith("(") && tag.endsWith(")")) {
                                paths.add(key);
                                return@forEach
                            }

                            if (includeModuleStyle.contains("lb") && tag.startsWith("{") && tag.endsWith("}")) {
                                paths.add(key);
                                return@forEach
                            }
                        }
                    }


                    if (includeApiStyle.size > 0) {
                        if (includeApiStyle.contains("mb") && obj.summary.startsWith("[") && obj.summary.endsWith("]")) {
                            paths.add(key);
                            return@forEach
                        }

                        if (includeApiStyle.contains("sb") && obj.summary.startsWith("(") && obj.summary.endsWith(")")) {
                            paths.add(key);
                            return@forEach
                        }

                        if (includeApiStyle.contains("lb") && obj.summary.startsWith("{") && obj.summary.endsWith("}")) {
                            paths.add(key);
                            return@forEach
                        }
                    }
                }
            }


            json.paths.removeAll { !it.IsIn(paths) }
        }


        SwaggerModel.swaggerInstance = json;
        //导入model
        if (part.isNullOrEmpty() || part == "model") {
            import_model(json, productLine, app, override ?: false)
        }

        //导入api
        if (part.isNullOrEmpty() || part == "api") {
            import_api(
                json, productLine, app,
                removePrefix, override ?: false
            )
        }
    }

    private fun import_api(
        json: SwaggerModel,
        productLine: ProductLine,
        app: String,
        removePrefix: String,
        override: Boolean
    ) {
        json.paths.forEach { path ->

            var url = path.key;

            if (path.key.startsWith(removePrefix, true)) {
                url = path.key.Slice(removePrefix.length);
            }

            var api = ApiDefine();
            var def: SwaggerRequestDef? = null;
            if (path.value.post != null) {
                api.httpMethod = HttpMethod.POST
                def = path.value.post
            } else if (path.value.get != null) {
                api.httpMethod = HttpMethod.GET
                def = path.value.get
            } else if (path.value.put != null) {
                api.httpMethod = HttpMethod.PUT
                def = path.value.put
            } else if (path.value.delete != null) {
                api.httpMethod = HttpMethod.DELETE
                def = path.value.delete
            }

            if (def == null) {
                return@forEach
            }

            api.productLine = CodeName(productLine.code, productLine.name);
            api.app = app;
            api.name = def.summary
            api.url = url;
            api.remark = def.description;

            if (api.group.isEmpty()) {
                api.group = def.tags.firstOrNull().AsString()
            }

            def.parameters.forEach { parameter ->
                var p = ApiSimpleParameterDefine();
                p.type = ApiParameterTypeEnum.loadWithSwaggerType(parameter.schema.get("type").AsString())
                p.key = parameter.name
                p.remark = parameter.description
                p.required = parameter.required
                if (parameter.`in` == "path") {
                    api.requestUrlPathParameters.add(p)
                } else if (parameter.`in` == "query") {
                    api.requestUrlQueryParameters.add(p)
                } else if (parameter.`in` == "header") {
                    api.requestHeaderParameters.add(p)
                } else if (parameter.`in` == "body") {
                    //这里是  @PostBody 格式
                    if (def.getRequestModelRef().HasValue) {
                        throw RuntimeException("${path.key} 不能同时有多个 @PostBody！");
                    }
                    api.requestBodyParameters.key = parameter.name
                    if (parameter.schema.contains("type")) {
                        api.requestBodyParameters.type =
                            ApiParameterTypeEnum.loadWithSwaggerType(parameter.schema.get("type").AsString())
                    } else if (parameter.schema.contains("${'$'}ref")) {
                        api.requestBodyParameters.type = ApiParameterTypeEnum.Object;

                        var modelType = json.getModel(parameter.schema.get("${'$'}ref").AsString());
                        api.requestBodyParameters.items.addAll(modelType.items)
                    }
                } else if (parameter.`in` == "formData") {
                    api.requestBodyParameters.key = parameter.name;
                    api.requestBodyParameters.type = ApiParameterTypeEnum.File
                } else {
                    throw RuntimeException("${path.key} 不识别参数位置: ${parameter.`in`}")
                }
            }


            if (def.getRequestModelRef().HasValue) {
                api.requestBodyParameters = json.getModel(def.getRequestModelRef())
            }

            if (def.getResponseModelRef().HasValue) {
                api.responseBodyParameters = json.getModel(def.getResponseModelRef())
            }


            var dbApi = mor.dev.apiDefine.query()
                .where { it.productLine.code mongoEquals api.productLine.code }
                .where { it.app mongoEquals api.app }
                .where { it.url mongoEquals api.url }
                .where { it.httpMethod mongoEquals api.httpMethod }
                .toEntity();

            if (dbApi == null) {
                mor.dev.apiDefine.doInsert(api);
            } else {

                dbApi.name = api.name
                dbApi.productLine = api.productLine
                dbApi.app = api.app
                dbApi.url = api.url
                dbApi.group = api.group

                dbApi.joinApi(api, override);
                mor.dev.apiDefine.updateWithEntity(dbApi).execUpdate()
            }
        }
    }

    private fun import_model(
        json: SwaggerModel,
        productLine: ProductLine,
        app: String,
        override: Boolean
    ) {
        json.models.forEach {
            var modelName = it.key;
            var model = it.value;
            if (model.isGenericType) {
                return@forEach
            }

            var apiModel = DataModel();
            apiModel.productLine = CodeName(productLine.code, productLine.name);
            apiModel.app = app;
            apiModel.cnName = modelName;
            apiModel.name = modelName;
            apiModel.remark = model.title;

            apiModel.define.type = ApiParameterTypeEnum.Object;
            apiModel.define.items.addAll(model.properties.map { it.toParameterDefine(listOf(it.value.ref)) });


            var dbModel = mor.dev.dataModel.query()
                .where { it.productLine.code mongoEquals apiModel.productLine.code }
                .where { it.app mongoEquals apiModel.app }
                .where { it.name mongoEquals apiModel.name }
                .toEntity();

            if (dbModel == null) {
                mor.dev.dataModel.doInsert(apiModel);
            } else {
                dbModel.productLine = apiModel.productLine
                dbModel.app = apiModel.app
                dbModel.name = apiModel.name


                dbModel.joinModel(apiModel, override)
                mor.dev.dataModel.updateWithEntity(dbModel)
                    .execUpdate();
            }
        }
    }


    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<ApiDefine> {
        mor.dev.apiDefine.queryById(id)
            .toEntity()
            .apply {
                if (this == null) {
                    return ApiResult.error("找不到数据")
                }

                return ApiResult.of(this)
            }
    }

    @ApiOperation("更新")
    @PostMapping("/save")
    fun save(
        @org.springframework.web.bind.annotation.RequestBody entity: ApiDefine,
        request: HttpServletRequest
    ): ApiResult<String> {
        //鉴权
        var userId = request.UserId;

        var ret = mor.dev.apiDefine.updateWithEntity(entity)
            .withColumns(request.requestParameterKeys)
            .run {
                if (entity.id.HasValue) {
                    return@run this.execUpdate()
                } else {
                    return@run this.execInsert()
                }
            }

        if (ret == 0) {
            return ApiResult.error("更新失败")
        }

        var defineId = entity.id;

        mor.dev.apiStory.query()
            .where { it.apis.apiDefine.id mongoEquals defineId }
            .toList()
            .forEach { story ->

                var index = -1;
                while (true) {
                    index++;
                    if (index >= story.apis.size) {
                        break;
                    }

                    if (story.apis[index].apiDefine.id != defineId) {
                        continue;
                    }

                    story.apis[index].apiDefine = entity
                }

                mor.dev.apiStory.updateWithEntity(story).execUpdate();
            }

        return ApiResult.of(entity.id)
    }


    @PostMapping("/clone/{id}")
    fun clone(@Require id: String): ApiResult<String> {
        var entity = mor.dev.apiDefine.queryById(id).toEntity()
        if (entity == null) {
            return ApiResult.error("找不到数据")
        }

        entity.id = "";

        var count = mor.dev.apiDefine.query()
            .where { it.name mongoStartsWith (entity.name + "-clone") }
            .count() + 1;

        entity.name = entity.name + "-clone" + count
        mor.dev.apiDefine.doInsert(entity);

        return ApiResult.of(entity.id)
    }

    @ApiOperation("删除")
    @PostMapping("/delete-query")
    fun delete_query(
        productLine: String,
        app: String,
        group: String,
        text: String,
        cnType: CnTypeEnum?
    ): JsonResult {
        mor.dev.apiDefine.delete()
            .apply {

//                if (productLine.HasValue) {
//                    this.linkOr({ it.productLine.code mongoEquals productLine },
//                        { it.productLine.name mongoEquals productLine })
//                }
//
//                if (app.HasValue) {
//                    this.where { it.app mongoLike app }
//                }
//
//                if (group.HasValue) {
//                    this.where { it.group mongoLike group }
//                }
//
//                if (cnType != null) {
//                    when (cnType) {
//                        CnInName -> this.where { it.name mongoPattern """\W""" }
//                        NoCnInName -> this.where { it.name mongoPattern """^\w+$""" }
//                        CnInField -> this.linkOr(
//                            { it.requestBodyParameters mongoPattern """\W""" },
//                            { it.requestHeaderParameters mongoPattern """\W""" },
//                            { it.requestUrlPathParameters mongoPattern """\W""" },
//                            { it.requestUrlQueryParameters mongoPattern """\W""" }
//                        )
//
//                        NoCnInField -> this.where(
//                            """function(){
//    var allEn = function(ary){
//        for(var i in ary) {
//            var remark = ary[i].remark;
//            if( !remark){
//                continue;
//            }
//
//            if( /\W/.test( remark ) ) {  return false   }
//        }
//        return true
//    };
//
//    return  ( this.requestHeaderParameters.length == 0  || allEn( this.requestHeaderParameters ) )
//             &&
//            (this.requestUrlPathParameters.length == 0 ||  allEn (this.requestUrlPathParameters) )
//            &&
//            (this.requestUrlQueryParameters.length == 0 ||  allEn (this.requestUrlQueryParameters) )
//             &&
//            (this.responseHeaderParameters.length == 0 ||  allEn (this.responseHeaderParameters) )
//             &&
//            (this.requestBodyParameters.items.length == 0 ||  allEn (this.requestBodyParameters.items) )
//             &&
//            (this.responseBodyParameters.items.length == 0 ||  allEn (this.responseBodyParameters.items) )
//}
//"""
//                        )
//                    }
//                }
//
//                if (text.HasValue) {
//                    this.linkOr(
//                        { it.productLine.code mongoLike text },
//                        { it.productLine.name mongoLike text },
//                        { it.app mongoLike text },
//                        { it.group mongoLike text },
//                        { it.name mongoLike text },
//                        { it.url mongoLike text },
//                        { it.remark mongoLike text })
//                }
            }
            .exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
                //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                return JsonResult()
            }
    }

    @ApiOperation("删除")
    @PostMapping("/batch-delete")
    fun batch_delete(
        @Require @org.springframework.web.bind.annotation.RequestBody ids: Array<String>
    ): JsonResult {
        mor.dev.apiDefine.delete()
            .where { it.id mongoIn ids }
            .exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
                //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                return JsonResult()
            }
    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    fun delete(
        @Require id: String,
        request: HttpServletRequest
    ): JsonResult {
        //鉴权
        var userId = request.UserId

        var entity = mor.dev.apiDefine.queryById(id).toEntity()
        if (entity == null) {
            return JsonResult.error("找不到数据")
        }

        mor.dev.apiDefine.deleteById(id)
            .exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
                //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                return JsonResult()
            }
    }
}